﻿using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using SBlogCore.Common.FriendlyException;
using SBlogCore.Common.JWTExtend.Models;

namespace SBlogCore.Common.App
{
    /// <summary>
    /// 
    /// </summary>
    [SkipScan]
    public static class AppBase
    {
        /// <summary>
        /// 所有的程序集
        /// </summary>
        public static IEnumerable<Assembly>? Assembly;
        public static void SetInstance(IApplicationBuilder provider) => Instance = provider.ApplicationServices;
        public static IServiceProvider Instance { get; private set; } = default!;
        /// <summary>
        /// 通过注入类型手动获取注入对象
        /// </summary>
        /// <param name="provider"></param>
        /// 该方法只能获取AddTransient和AddSingleton注入的对象，不能获取AddScoped（请求生命周期内唯一）注入的对象
        public static T GetService<T>()
        {
            var valueservice = Instance.GetService<T>();
            if (valueservice==null)
            {
                throw new Exception($"未找到{typeof(T).Name}的实现");
            }
            return valueservice!;
        }
        /// <summary>
        /// 获取登录用户的JWT信息
        /// </summary>
        /// <returns></returns>
        public static TokenModelJwt? GetJwtUser()
        {
            try
            {
                var httpContextAccessor = GetService<IHttpContextAccessor>();
                var user= httpContextAccessor?.HttpContext?.Request.GetTokenUser();
                if (user == null)
                    throw SBlogCoreException.Say("登录异常");
                return user;
            }
            catch (Exception e)
            {
                return null;
            }
        }
    }
}
